using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using SolutionFactory.Services;

namespace SolutionFactory.Exporter
{
    public class FileCopyAndTokenReplacer
    {
        private readonly FileSystem _fileSystem;
        private readonly ILogger _logger;
        private readonly FileTokenReplacer _fileTokenReplacer;

        public FileCopyAndTokenReplacer(FileSystem fileSystem,ILogger logger,FileTokenReplacer fileTokenReplacer)
        {
            _fileSystem = fileSystem;
            _logger = logger;
            _fileTokenReplacer = fileTokenReplacer;            
        }

        public void InitializeTokenReplacer(string name)
        {
            var dictionary = new Dictionary<string, string>();
            dictionary.Add(name, "$safesolutionname$");
			dictionary.Add(name.ToLower(), "$safesolutionname$");
            _fileTokenReplacer.SetTokens(dictionary);
        }




        public void CopyNonSolutionFiles(string destinationDirectory, string trunkPath, string solutionSubDirectory)
        {
            CopyTrunkDirectories(trunkPath, solutionSubDirectory, destinationDirectory);
        }

        private void CopyTrunkDirectories(string solutionDirRoot, string solutionParentDir, string dir)
        {
        	foreach (var filename in _fileSystem.GetFilesInDirectory(solutionDirRoot,"*.*"))
        	{
				_logger.Log("Copying " + filename);
				string targetFile = Path.Combine(dir, _fileSystem.GetFileNameWithExtension(filename));				
				_fileSystem.Copy(filename, targetFile);        			
        	}

            foreach (string subDirectory in _fileSystem.GetSubDirectories(solutionDirRoot))
            {
                string subDirName = subDirectory.Replace(solutionDirRoot, "");
                if (subDirName != solutionParentDir && !subDirName.StartsWith("."))
                {
                    _logger.Log("Copying " + subDirectory);
                    string targetDir = Path.Combine(dir, subDirName);
                    string sourceDir = Path.Combine(solutionDirRoot, subDirName);
                    _fileSystem.CopyFilesAndDirectories(sourceDir, targetDir);
                }
            }
        }

    	public void CopySolutionFiles(string destinationDir, string sourceDir)
    	{
			CopyTrunkDirectories(sourceDir, "", destinationDir);
		}
    }
}